package com.ybkj.daijia.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.SignHelper;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.ActivityCouponRule;
import com.ybkj.daijia.server.sales.ActivityManage;
import com.ybkj.daijia.server.sales.ActivityRecord;
import com.ybkj.daijia.server.sales.ActivityVo;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

@Component
public class SalesApi {

    /**
     * 插入优惠券规则
     */
    public static final String CREATE_COUPONRULE = "api/couponrules/create";
    /**
     * 查询优惠券规则信息
     */
    public static final String FINDALL_COUPONRULE = "api/couponrules/findAll";
    /**
     * 根据id优惠券规则信息
     */
    public static final String FINDBYID_COUPONRULE = "api/couponrules/findById";
    /**
     * 删除优惠券规则
     */
    public static final String DELETE_COUPONRULE = "api/couponrules/delete";
    /**
     * 失效优惠券规则
     */
    public static final String LAPSED_COUPONRULE = "api/couponrules/lapsed";
    /**
     * 有效优惠券规则
     */
    public static final String FINDVALID_COUPONRULE = "api/couponrules/findValid";
    /**
     * 根据id查询单个优惠券
     */
    public static final String ONE_COUPON = "api/coupons/findOne/{id}";
    /**
     * 根据code查询单个优惠券
     */
    public static final String ONE_COUPON_CODE = "api/coupons/findOneByCode/{couponCode}";
    /**
     * 生成优惠券
     */
    public static final String MASS_COUPON = "api/coupons/mass";
    /**
     * 查询优惠券
     */
    public static final String FIND_COUPON = "api/coupons/findCoupon";
    /**
     * 导出优惠券
     */
    public static final String EXPORT_COUPON = "api/coupons/export";
    /**
     * 失效优惠券
     */
    public static final String INVALID_COUPON = "api/coupons/invalid";
    /**
     * 手动赠送优惠券
     */
    public static final String GIFTCOUPON_COUPON = "api/coupons/giftcoupon";
    /**
     * 根据客户id查询有效优惠券
     */
    public static final String FIND_VALID_COUPON = "api/coupons/listValidByPassenger";
    /**
     * 根据客户id分页查询优惠券
     */
    public static final String QUERY_COUPON = "api/coupons/queryByPassenger";
    /**
     * 修改优惠券
     */
    public static final String UPDATE_COUPON = "api/coupons/update/";
    /**
     * 根据客户查询优惠券金额
     */
    public static final String SUM_COUPON_MONEY = "api/coupons/sumMoneyByPassenger/";
    /**
     * 插入优惠券 旧数据导入用
     */
    public static final String CREATE_COUPON = "api/coupons/create";
    /**
     * 分页查询活动
     */
    public static final String QUERY_ACTIVITIES = "api/activity/queryActivities";
    /**
     * 新增活动
     */
    public static final String CREATE_ACTIVITY = "api/activity/create";
    /**
     * 新增活动
     */
    public static final String UPDATE_ACTIVITY = "api/activity/update";
    /**
     * 开始活动
     */
    public static final String START_ACTIVITY = "api/activity/startActivity";
    /**
     * 开始活动
     */
    public static final String START_ACTIVITY_V4 = "api/activity/startActivityV4";
    /**
     * 停止活动
     */
    public static final String STOP_ACTIVITY = "api/activity/stopActivity/{activityId}";
    /**
     * 删除活动
     */
    public static final String DELETE_ACTIVITY = "api/activity/deleteActivity/{activityId}";
    /**
     * 根据id查询单个活动
     */
    public static final String ONE_ACTIVITY = "api/activity/{activityId}";
    /**
     * 根据id查询单个活动
     */
    public static final String VALID_ACTIVITY = "api/activity/findValidByEvent";
    /**
     * 根据公司id查询单个首单免费活动
     */
    public static final String ONEFREE_ACTIVITY = "api/activity/findOneFree";
    /**
     * 根据手机号赠送优惠券
     */
    public static final String PHONE_ACTIVITY = "api/activity/phonecoupon";
    /**
     * 查询所有活动
     */
    public static final String ACTIVITYALL_ACTIVITY = "api/activity/activityAll";
    /**
     * 查询活动记录
     */
    public static final String QUERY_ACTIVITY_RECORD = "api/activityrecord/queryByActivity";
    /**
     * 统计活动记录条数
     */
    public static final String COUNT_BY_PARAM = "api/activityrecord/countByParam";

    //活动
    /**
     * 查询活动记录数量
     */
    public static final String COUNT_ACTIVITY_RECORD = "api/activityrecord/countActivityRecord";
    /**
     * 查询单个活动记录
     */
    public static final String ONE_ACTIVITY_RECORD = "api/activityrecord/{recordId}";
    /**
     * 分页查询活动信息
     */
    public static final String QUERY_ACTIVITYMANAGE = "api/activitymanage/queryActivityManage";
    /**
     * 根据公司id查询活动信息
     */
    public static final String QUERY_BYCOMPANYID = "api/activitymanage/queryByCompanyId";
    /**
     * 创建活动信息
     */
    public static final String CREATE_ACTIVITYMANAGE = "api/activitymanage/create";
    /**
     * 删除活动信息
     */
    public static final String DELETE_ACTIVITYMANAGE = "api/activitymanage/delete";
    /**
     * 根据id查询活动信息
     */
    public static final String ONE_ACTIVITYMANAGE = "api/activitymanage/{activityId}";
    /**
     * 修改活动信息
     */
    public static final String UPDATE_ACTIVITYMANAGE = "api/activitymanage/update";
    /**
     * 根据活动id查询活动所有优惠券
     */
    public static final String FIND_ACTIVITYCOUPONRULR = "api/activityRule/findByActivityId";
    /**
     * 根据活动优惠券规则id查询
     */
    public static final String FIND_COUPONRULR = "api/activityRule/findByCouponRuleId";
    private static final Logger logger = LoggerFactory.getLogger(SalesApi.class);
    @Value("${module.couponRule.url}")
    private String couponRuleBaseURL;
    @Value("${module.couponRule.appId}")
    private String couponRuleAppid;
    @Value("${module.couponRule.appKey}")
    private String couponRuleAppkey;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SettingUtils settingUtils;

    //活动信息

    public String getCouponRuleBaseURL() {
        return couponRuleBaseURL.endsWith("/") ? couponRuleBaseURL : couponRuleBaseURL + "/";
    }

    public void setCouponRuleBaseURL(String couponRuleBaseURL) {
        this.couponRuleBaseURL = couponRuleBaseURL;
    }

    public String CouponRule() {
        return couponRuleAppid;
    }

    public void setCouponRuleAppid(String couponRuleAppid) {
        this.couponRuleAppid = couponRuleAppid;
    }

    public String getCouponRuleAppkey() {
        return couponRuleAppkey;
    }

    public void setCouponRuleAppkey(String couponRuleAppkey) {
        this.couponRuleAppkey = couponRuleAppkey;
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String get(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), couponRuleAppkey);

        kv.put("sign", sign);
        kv.put("appId", couponRuleAppid);

        String result = null;

        try {
            result = restTemplate.getForObject(apiurl, String.class, kv);
        } catch (HttpClientErrorException e) {
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        }
        return result;

    }


    public String post(String apiurl, MultiValueMap<String, String> kv, Setting setting) {

        kv.add("appKey", setting.getSecKey());

        Set<Entry<String, List<String>>> entries = kv.entrySet();

        Map<String, String> params = new HashMap<String, String>();
        for (Entry<String, List<String>> entry : entries) {
            List<String> values = entry.getValue();
            params.put(entry.getKey(), CollectionUtils.isEmpty(values) ? null : values.get(0));
        }

        String sign = SignHelper.sign(SignHelper.buildSignMessage(params), couponRuleAppkey);

        kv.add("sign", sign);
        kv.add("appId", couponRuleAppid);

        logger.error("couponRuleAppid:{}", couponRuleAppid);

        RestTemplate rest = new RestTemplate();

        String result = null;

        try {
            result = rest.postForObject(apiurl, kv, String.class);
        } catch (HttpClientErrorException e) {
            logger.error("HttpClientErrorException:code:{},status:{},body:{}", e.getStatusCode(),
                e.getStatusText(), e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            logger.error("HttpServerErrorException:{}", e.getResponseBodyAsString());
            result = e.getResponseBodyAsString();
        }

        return result;
    }

    public String put(String apiurl, Map<String, String> kv, Setting setting) {
        kv.put("appKey", setting.getSecKey());

        String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), couponRuleAppkey);

        kv.put("sign", sign);
        kv.put("appId", couponRuleAppid);

        String result = null;
        try {
            restTemplate.put(apiurl, null, kv);
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return result;

    }

    public String delete(String apiurl, Map<String, String> kv, Setting setting) {

        kv.put("appKey", setting.getSecKey());

        String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), couponRuleAppkey);

        kv.put("sign", sign);
        kv.put("appId", couponRuleAppid);
        String result = null;
        try {
            restTemplate.delete(apiurl, kv);
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return result;

    }

    public Result<ActivityVo> startActivity(Activity activity, Passenger passenger,
        Enterprise enterprise) {

        Result<ActivityVo> result = new Result<ActivityVo>();
        result.setSuccess(false);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("activityId", activity.getId().toString());

        kv.add("passengerId", String.valueOf(passenger.getId()));

        if (null != enterprise) {
            kv.add("enterpriseId", String.valueOf(enterprise.getId()));
        }

        String resultStr = post(getCouponRuleBaseURL() + SalesApi.START_ACTIVITY_V4, kv,
            settingUtils.get());

        ActivityVo activityVo = null;

        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activityVo = gson.fromJson(data.toString(), ActivityVo.class);
                    result.setResult(activityVo);
                    result.setSuccess(true);
                }
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }

        return result;

    }

    public Result<Activity> findOneActivity(Long activityId) {
        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        Activity activity = null;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONE_ACTIVITY;
        api = api.replaceAll("\\{activityId\\}", String.valueOf(activityId));
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activity = gson.fromJson(data.toString(), Activity.class);
                    result.setResult(activity);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<ActivityRecord> findOneActivityRecord(Long recordId) {

        Result<ActivityRecord> result = new Result<ActivityRecord>();
        result.setSuccess(false);

        ActivityRecord activityRecord = null;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONE_ACTIVITY_RECORD;
        api = api.replaceAll("\\{recordId\\}", String.valueOf(recordId));
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activityRecord = gson.fromJson(data.toString(), ActivityRecord.class);
                    result.setResult(activityRecord);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;

    }

    public Result<Activity> findValidByEvent(ActivityEvent activityEvent) {
        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.VALID_ACTIVITY;
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        sb.append("&activityEvent={activityEvent}");
        kv.put("activityEvent", activityEvent.toString());

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        List<Activity> activities = new ArrayList<Activity>();
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activities = gson.fromJson(data.toString(), new TypeToken<List<Activity>>() {
                    }.getType());
                    result.setData(activities);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<ActivityCouponRule> findByActivity(Long activityId) {
        Result<ActivityCouponRule> result = new Result<ActivityCouponRule>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.FIND_ACTIVITYCOUPONRULR;
        sb.append(getCouponRuleBaseURL() + api + "?appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        sb.append("&activityId={activityId}");
        kv.put("activityId", activityId.toString());

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        List<ActivityCouponRule> list = new ArrayList<ActivityCouponRule>();
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    list = gson
                        .fromJson(data.toString(), new TypeToken<List<ActivityCouponRule>>() {
                        }.getType());
                    result.setData(list);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }


    public Result<Activity> findOneByCompanyId(Long companyId) {
        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONEFREE_ACTIVITY;
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        sb.append("&companyId={companyId}");
        kv.put("companyId", String.valueOf(companyId));

        String resultStr = get(sb.toString(), kv, settingUtils.get());

/*		Activity activitity=new Activity();
		if (StringUtils.isNotBlank(resultStr)) {
			JSONObject jo = new JSONObject(resultStr);
			Integer code = jo.getInt("code");
			if (code == 0) {
				Object object=jo.get("data");
				if(null!=object && !object.toString().equals("null")){
					JSONObject data = jo.getJSONObject("data");
					Gson gson=new Gson();
					activitity = gson.fromJson(data.toString(), Activity.class);
					result.setResult(activitity);
				}
				result.setSuccess(true);
			} else {
				result.setSuccess(false);
				result.setMessage(jo.getString("message"));
			}
		}*/
        List<Activity> activities = new ArrayList<Activity>();
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activities = gson.fromJson(data.toString(), new TypeToken<List<Activity>>() {
                    }.getType());
                    result.setData(activities);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<ActivityManage> findOneActivityManage(Long activityId) {
        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        ActivityManage activityManage = null;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONE_ACTIVITYMANAGE;
        api = api.replaceAll("\\{activityId\\}", String.valueOf(activityId));
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        String resultStr = get(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    activityManage = gson.fromJson(data.toString(), ActivityManage.class);
                    result.setResult(activityManage);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<Coupon> findOneCoupon(Long couponId) {
        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        Coupon coupon = null;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONE_COUPON;
        api = api.replaceAll("\\{id\\}", String.valueOf(couponId));
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    coupon = gson.fromJson(data.toString(), Coupon.class);
                    result.setResult(coupon);

                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<Coupon> findOneCouponByCode(String couponCode) {
        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        Coupon coupon = null;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.ONE_COUPON_CODE;
        api = api.replaceAll("\\{couponCode\\}", couponCode);
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    coupon = gson.fromJson(data.toString(), Coupon.class);
                    result.setResult(coupon);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<CouponRule> findOneCouponRule(Long id) {

        Result<CouponRule> result = new Result<CouponRule>();
        result.setSuccess(false);

        CouponRule couponRule = null;

        StringBuilder builder = new StringBuilder();
        builder.append(getCouponRuleBaseURL() + SalesApi.FINDBYID_COUPONRULE
            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("id", String.valueOf(id));
        builder.append("&id={id}");

        String resultStr = get(builder.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    couponRule = gson.fromJson(data.toString(), CouponRule.class);
                    result.setResult(couponRule);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    public Result<Coupon> updateCoupon(Coupon coupon) {

        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        sb.append(getCouponRuleBaseURL()
            + UPDATE_COUPON
            + coupon.getId()
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        if (null != coupon.getPassengerId()) {
            kv.put("passengerId", String.valueOf(coupon.getPassengerId()));
            sb.append("&passengerId={passengerId}");
        }

        if (StringUtils.isNotBlank(coupon.getPhone())) {
            kv.put("passengerPhone", coupon.getPhone());
            sb.append("&passengerPhone={passengerPhone}");
        }

        if (null != coupon.getStatus()) {
            kv.put("status", String.valueOf(coupon.getStatus()));
            sb.append("&status={status}");
        }

        String resultStr = put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;
    }

    public BigDecimal sumMoneyByPassenger(Long passengerId) {

        BigDecimal money = BigDecimal.ZERO;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.SUM_COUPON_MONEY + passengerId;
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = get(sb.toString(), kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    money = new BigDecimal(jo.getDouble("data"));
                }
            } else {

            }
        }

        return money;

    }

    public Long countActivityRecord(Long passengerId, Long activityId) {

        Long times = 0L;
        ;

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.COUNT_ACTIVITY_RECORD;
        sb.append(getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        kv.put("passengerId", String.valueOf(passengerId));
        sb.append("&passengerId={passengerId}");

        kv.put("activityId", String.valueOf(activityId));
        sb.append("&activityId={activityId}");

        String resultStr = get(sb.toString(), kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    times = jo.getLong("data");
                }
            } else {

            }
        }

        return times;

    }

    public Result<ActivityCouponRule> findByCoupon(Long couponRuleId) {
        Result<ActivityCouponRule> result = new Result<ActivityCouponRule>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.FIND_COUPONRULR;
        sb.append(getCouponRuleBaseURL() + api + "?appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        sb.append("&couponRuleId={couponRuleId}");
        kv.put("couponRuleId", couponRuleId.toString());

        String resultStr = get(sb.toString(), kv, settingUtils.get());

        List<ActivityCouponRule> list = new ArrayList<ActivityCouponRule>();
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object object = jo.get("data");
                if (null != object && !object.toString().equals("null")) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    list = gson
                        .fromJson(data.toString(), new TypeToken<List<ActivityCouponRule>>() {
                        }.getType());
                    result.setData(list);
                }
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }


}
